'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('messages', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      contactId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'contacts',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      direction: {
        type: Sequelize.ENUM('inbound', 'outbound'),
        allowNull: false
      },
      content: {
        type: Sequelize.TEXT,
        allowNull: true
      },
      contentType: {
        type: Sequelize.STRING,
        defaultValue: 'text'
      },
      originalContent: {
        type: Sequelize.TEXT,
        allowNull: true
      },
      hasSensitive: {
        type: Sequelize.BOOLEAN,
        defaultValue: false
      },
      mediaUrl: {
        type: Sequelize.STRING,
        allowNull: true
      },
      mimeType: {
        type: Sequelize.STRING,
        allowNull: true
      },
      whatsappMessageId: {
        type: Sequelize.STRING,
        allowNull: true
      },
      status: {
        type: Sequelize.ENUM('pending', 'sent', 'delivered', 'read', 'failed'),
        defaultValue: 'sent'
      },
      isRead: {
        type: Sequelize.BOOLEAN,
        defaultValue: false
      },
      userId: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'users',
          key: 'id'
        }
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });

    // 创建索引
    await queryInterface.addIndex('messages', ['contactId']);
    await queryInterface.addIndex('messages', ['whatsappMessageId']);
    await queryInterface.addIndex('messages', ['createdAt']);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('messages');
  }
};
